package com.jfs.qy.config;

import com.jfs.qy.config.component.TaskExecutorReactor;
import com.jfs.qy.config.component.TaskExecutorReactorRealization;
import com.jfs.qy.config.component.TaskThreadFactory;
import com.jfs.qy.properties.AsyncExecutorProperties;
import com.jfs.qy.properties.ExecutorProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @Description 线程池配置、启用异步
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/11/4
 */
@Configuration
@EnableAsync(proxyTargetClass = true)
@EnableConfigurationProperties(value = { ExecutorProperties.class, AsyncExecutorProperties.class})
public class AsyncTaskExecutorConfig {


    /**
     *配置定时任务线程池
     * @param beatExecutorProperties
     * @return
     */
    @Bean
    public ScheduledExecutorService executor(ExecutorProperties beatExecutorProperties) {
        return Executors.newScheduledThreadPool(beatExecutorProperties.getCorePoolSize(),
                new TaskThreadFactory(beatExecutorProperties.getThreadNamePrefix()));
    }

    /**
     * 配置定时任务工具组件
     * @param scheduledExecutorService
     * @return
     */
    @Bean
    public TaskExecutorReactor healthCheckReactor(@Qualifier("executor") ScheduledExecutorService scheduledExecutorService) {
        return new TaskExecutorReactorRealization(scheduledExecutorService);
    }


    /**
     *
     * 配置异步线程池
     * @param asyncExecutorProperties
     * @return
     */
   /* @Bean(name = AsyncExecutorProperties.BEAN_NAME)
    public Executor asyncServiceExecutor(AsyncExecutorProperties asyncExecutorProperties) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(asyncExecutorProperties.getCorePoolSize());
        //配置最大线程数
        executor.setMaxPoolSize(asyncExecutorProperties.getMaxPoolSize());
        //配置队列大小
        executor.setQueueCapacity(asyncExecutorProperties.getQueueCapacity());
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(asyncExecutorProperties.getNamePrefix());
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }*/


}
